<!--
 * @Description:
 * @Autor: 刘诗文
 * @Date: 2020-11-30 17:03:53
 * @LastEditors: 刘诗文
 * @LastEditTime: 2020-12-03 19:57:07
-->
<template>
  <div>
    <div>
      <FormPanel ref="formPanel" :list="formList" :cols="3" :labelWidth="80" :formType="type" :isSubmitBtn="false" />
    </div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="cancelHandle">取消</el-button>
      <AjaxButton type="primary" :click="saveHandler" v-if="addVisable === true">保存</AjaxButton>
    </div>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { notifyAction } from '@/utils';
import { getPinpSelect, getChexSelect, getCheModelSelect } from '@/api/repair/repairReception/customer/brand.js';
import { getUserListSelect } from '@/api/customerRepair/rescueManagement/rescueOrder';
import { getSettingNo, saveSettings, findAllSettings } from '@/api/customerRepair/visitRules/returnVisitSettings';

export default {
  name: 'addSettings',
  mixins: [dictionary],
  props: {
    type: {
      type: String
    },
    formData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      formList: this.createFromList(),
      carePeopleItemList: [],
      settingId: '',
      addVisable: true
    };
  },
  mounted() {
    // 获取品牌
    this.getBrand();
    // 获取客服专员
    this.getHandler();
    if (this.type === 'add') {
      // 获取计划单号
      this.getSettingNoFun();
    } else if (this.type === 'edit') {
      // 获取页面数据
      this.getcarePeople();
    } else if (this.type === 'detail') {
      this.addVisable = false;
      // 获取页面数据
      this.getcarePeople();
    }
    console.log(this.type);
  },
  methods: {
    createFromList() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '新增回访计划'
        },
        {
          type: 'INPUT',
          label: '计划编号',
          fieldName: 'settingNo',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '回访类型',
          fieldName: 'type',
          disabled: true,
          initialValue: 12631002,
          itemList: this.createDictList(1263)
        },
        {
          type: 'INPUT',
          label: '回访名称',
          fieldName: 'settingName',
          initialValue: '',
          disabled: this.type === 'detail' ? true : false,
          rules: [{ required: true, message: '请填写回访名称', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '基准日期',
          fieldName: 'baseDateType',
          disabled: true,
          initialValue: 0,

          itemList: [{ text: '出库日期', value: 0 }]
        },
        {
          type: 'INPUT',
          label: '据基准日期后',
          fieldName: 'baseDate',
          labelWidth: '30',
          initialValue: '',
          selfCols: 2,
          descOptions: {
            content: '天产生回访信息'
          },
          disabled: this.type === 'detail' ? true : false,
          style: { width: 'calc(100% - 180px)' }
        },
        {
          type: 'INPUT',
          label: '产生任务后',
          fieldName: 'produceDate',
          labelWidth: '30',
          initialValue: '',
          selfCols: 2,
          descOptions: {
            content: '天需要回访'
          },
          disabled: this.type === 'detail' ? true : false,
          style: { width: 'calc(100% - 180px)' }
        },
        {
          type: 'SELECT',
          label: '是否启用',
          fieldName: 'status',
          initialValue: 10041001,
          disabled: this.type === 'detail' ? true : false,
          itemList: this.createDictList(1004)
        },
        {
          type: 'BREAK_SPACE',
          label: '关爱对象设置'
        },
        {
          type: 'RANGE_DATE',
          label: '出库日期',
          fieldName: 'outDateBeg|outDateEnd',
          initialValue: [],
          disabled: this.type === 'detail' ? true : false
        },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'brand',
          disabled: this.type === 'detail' ? true : false,
          itemList: [],
          change: val => {
            this.getSeries(val);
          }
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'series',
          disabled: this.type === 'detail' ? true : false,
          itemList: [],
          change: val => {
            this.getModel(this.findFormItem('brand').initialValue, val);
          }
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'model',
          disabled: this.type === 'detail' ? true : false,
          itemList: []
        },
        {
          type: 'BREAK_SPACE',
          label: '关爱人员设置'
        },
        {
          type: 'RADIO',
          label: '分配规则',
          fieldName: 'rule',
          disabled: this.type === 'detail' ? true : false,
          initialValue: 12621001,
          selfCols: 3,
          itemList: [
            { text: '归属人', value: 12621001 },
            { text: '关爱人（任务将平均分配勾选人员）', value: 12621002 }
          ],
          change: val => {
            if (val === 12621001) {
              this.findFormItem('carePeople').disabled = true;
              this.findFormItem('carePeople').initialValue = '';
            } else if (val === 12621002) {
              this.findFormItem('carePeople').disabled = false;
            }
          }
        },
        {
          type: 'MULTIPLE_CHECKBOX',
          label: '关爱人员',
          fieldName: 'carePeople',
          itemList: [],
          selfCols: 3,
          disabled: true
        }
      ];
    },
    // 取表单通用方法
    findFormItem(fieldName) {
      return this.formList.find(x => x.fieldName === fieldName) || {};
    },
    // 品牌
    async getBrand() {
      const res = await getPinpSelect();
      this.formList.find(item => item.fieldName === 'brand').itemList = res.data.map(x => ({
        value: x.brandId + '',
        text: x.brandName
      }));
    },
    // 车系
    async getSeries(brandsid) {
      const res = await getChexSelect(brandsid);
      this.formList.find(item => item.fieldName === 'series').itemList = res.data.map(x => ({
        value: x.seriesId + '',
        text: x.seriesName
      }));
    },
    // 车型
    async getModel(brandsid, seriessid) {
      const res = await getCheModelSelect(brandsid, seriessid);
      this.formList.find(item => item.fieldName === 'model').itemList = res.data.map(x => ({
        value: x.modelId + '',
        text: x.modelName
      }));
    },
    // 获取客服专员
    async getHandler() {
      const res = await getUserListSelect();
      if (res.resultCode === 200) {
        if (res.errMsg) {
          notifyAction(res.errMsg, 'warning');
        } else {
          this.formList.find(item => item.fieldName === 'carePeople').itemList = this.carePeopleItemList = res.data.map(x => ({
            value: x.userId + '',
            text: x.employeeName
          }));
        }
      }
    },
    // 获取计划单号
    async getSettingNoFun() {
      const res = await getSettingNo();
      if (res.resultCode === 200) {
        if (res.errMsg) {
          notifyAction(res.errMsg, 'error');
        } else {
          this.findFormItem('settingNo').initialValue = res.data;
        }
      }
    },
    // 保存
    async saveHandler() {
      const [err, data] = await this.$refs.formPanel.GET_FORM_DATA();
      if (err) return;
      const carePeopleList = [];
      data.carePeople.forEach(y => {
        const userName = this.carePeopleItemList.find(x => x.value === y).text;
        carePeopleList.push({ userId: y, userName: userName });
      });
      console.log(carePeopleList);
      if (this.type === 'edit') {
        data.settingId = this.settingId;
      }
      const res = await saveSettings({ ...data, carePeopleList: carePeopleList });
      if (res.resultCode === 200) {
        if (res.errMsg) {
          notifyAction(res.errMsg, 'error');
        } else {
          notifyAction('保存成功！');
          this.cancelHandle();
        }
      }
    },
    // 取消
    cancelHandle() {
      this.$emit('close', false);
    },
    // 编辑或明细查询数据
    async getcarePeople() {
      console.log(this.formData);
      const res = await findAllSettings({ settingId: this.formData.settingId, settingNo: this.formData.settingNo });
      if (res.resultCode === 200) {
        if (res.errMsg) {
          notifyAction(res.errMsg, 'error');
        } else {
          // 往页面赋值
          this.settingId = res.data.rows[0]['settingId'];
          console.log(res.data.rows[0]['outDateBeg']);
          console.log(res.data.rows[0]['outDateEnd']);
          console.log(this.findFormItem('outDateBeg|outDateEnd'));
          console.log(this.findFormItem('outDateBeg|outDateEnd').initialValue);
          this.formList.forEach(x => {
            x.initialValue = res.data.rows[0][x.fieldName];
          });
          this.findFormItem('outDateBeg|outDateEnd').initialValue = [res.data.rows[0]['outDateBeg'], res.data.rows[0]['outDateEnd']];
          const peopleList = [];
          if (this.type === 'edit' && this.findFormItem('rule').initialValue === 12621002) {
            res.data.rows[0].carePeopleList.forEach(x => {
              peopleList.push(x.userId);
            });
            this.findFormItem('carePeople').initialValue = peopleList;
            this.findFormItem('carePeople').disabled = false;
          }
          this.getSeries(this.findFormItem('brand').initialValue);
          this.getModel(this.findFormItem('brand').initialValue, this.findFormItem('series').initialValue);
        }
      }
    }
  }
};
</script>
<style lang="less" scoped></style>
